#!/bin/bash
DEPLOY_DIR=`pwd`
#路径地址
PAYMENT_DIR=$DEPLOY_DIR
# 容器名称
PAYMENT_DOCKER_NAME=payment
# 远端容器 镜像仓库
REMOTE_DOCKER_PAYMENT=ccr.ccs.tencentyun.com/jack_lq/jack_pay:5-20


#mvn 项目打包
function clean() {
  rm -rf $PAYMENT_DIR/distribution
  mvn clean install
}
# 构建容器
function start_builder() {
  local work_dir=$1
  local local_docker_name=$2
  local remote_docker_url=$3
  # 检查工作目录是否存在
  if [ ! -d "$work_dir" ]; then
    echo "work path $work_dir not find"
    exit 1
  fi
  clean
  docker images | grep $local_docker_name &> /dev/null
  if [ $? -eq 0 ]; then
      echo "Find and remove" $local_docker_name  ", we will from  docker in remove it!!!"
      docker rmi -f $local_docker_name
  fi
  cd $work_dir
  # 构建本地docker 镜像
  if ! docker build -t $local_docker_name .; then
      echo "Docker images build fail"
      exit 1
  fi
  # 将本地docker 镜像 与远端进行标记
  if ! docker tag $local_docker_name $remote_docker_url; then
      echo "Docker images tag fail"
      exit 1
  fi
  # 将Docker镜像推送到远程仓库
  if ! docker push $remote_docker_url; then
      echo "Docker images push fail"
      exit 1
  fi
}

#清除所有旧的镜像
function old() {
  docker rmi $(docker images | grep 'none' | awk '{print $3}')
}

# 根据不同的输入类型, 执行不同docker 构建程序
case "$1" in
 #清除老容器
  'old')
    old
    ;;
  # 构建
  'install')
    clean
    ;;
  'payment')
    start_builder $PAYMENT_DIR $PAYMENT_DOCKER_NAME $REMOTE_DOCKER_PAYMENT
   ;;
esac